// ==UserScript==
// @name         Automatizaciones Integra
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Example Script with Hotkey
// @include      *://portalitss.meyss.es/*
// ==/UserScript==


(function() {

    let currentElement = "";

    //////////////////////////////
    //
    //          INICIO
    //    Definicion de hotkeys
    //
    //////////////////////////////

    const scriptHotkeys = document.createElement('script');
    scriptHotkeys.src = 'https://cdnjs.cloudflare.com/ajax/libs/mousetrap/1.6.5/mousetrap.min.js';
    scriptHotkeys.onload = function() {
        // FUNCIONES AUXILIARES
        function getElementByXPath(path) {
            return new XPathEvaluator()
                .createExpression(path)
                .evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)
                .singleNodeValue;
        }
        function sleep(time) {
            return new Promise((resolve) => setTimeout(resolve, time));
        }
        async function waitForElement(xpath) {
            do {
                currentElement = getElementByXPath(xpath);
                await sleep(20);
            } while (!currentElement);
        }
        // FIN FUNCIONES AUXILIARES


        let currentHotkey = localStorage.getItem("CurrentHotkey");
        console.log("CurrentHotkey: " + currentHotkey);

        // HOTKEY 1 ARCHIVO
        Mousetrap.bind('ctrl+j', async function(e) {
            e.preventDefault(); // Prevent default behavior of hotkey

            currentElement = document.getElementById('formulario:barraPestannas:pesAnotaciones:pestanna-pesAnotaciones');
            localStorage.setItem("CurrentHotkey", "HK1STAGE1");
            currentElement.click();
        });
        if (currentHotkey == "HK1STAGE1") {
            let currentElement = document.getElementById('formulario:linkCambiaModoEdicion');
            if (currentElement) {
                localStorage.setItem("CurrentHotkey", "HK1STAGE2");
                currentElement.click();
            } else {
                console.log('Element not found linkCambiaModoEdicion');
            }
        }
        if (currentHotkey == "HK1STAGE2") {
            let currentElement = document.getElementById('formulario:transferidoCheck');
            if (currentElement) {
                if (!currentElement.checked) {
                    currentElement.click();
                }
                currentElement = document.getElementById('formulario:guardarArchivo');
                currentElement.click();
                localStorage.setItem("CurrentHotkey", "");

            } else {
                console.log('Element not found transferidoCheck');
            }
        }
        // FIN HOTKEY 1 ARCHIVO

        // HOTKEY 2 VISAR O FINALIZAR
        Mousetrap.bind('ctrl+o', async function(e) {
            e.preventDefault(); // Prevent default behavior of hotkey

            currentElement = document.getElementById('formulario:j_idt960:editarOrd:control-editarOrd');
            currentElement.click();
            await waitForElement('//*[@id="formulario:j_idt960:guardar:control-guardar"]');

            currentElement = document.getElementById('formulario:listaEstados_focus');
            if (currentElement) {
                currentElement.focus();
                currentElement = document.getElementById('formulario:listaEstados_input');
                if (currentElement.options[currentElement.selectedIndex].text == "Actuaciones Concluidas") {
                    let optionLabels = Array.from(currentElement.options).map((opt) => opt.text);
                    if (optionLabels.includes("Visado")) {
                        currentElement.value = "12"; // Seleccionar Visado
                        currentElement.dispatchEvent(new Event('change'));
                        await waitForElement('//*[@id="formulario:labelVisador:selectVisador_focus"]');
                        currentElement = document.getElementById('formulario:labelVisador:selectVisador_focus');
                        currentElement.focus();
                    }
                    if (optionLabels.includes("Finalizada")) {
                        currentElement.value = "8"; // Seleccionar Finalizada
                        currentElement.dispatchEvent(new Event('change'));
                        await waitForElement('//*[@id="formulario:final_focus"]');
                        await sleep(500);
                        currentElement = document.getElementById('formulario:final_focus');
                        currentElement.focus();
                    }
                }
                if (currentElement.options[currentElement.selectedIndex].text == "Visado") {
                    let optionLabels = Array.from(currentElement.options).map((opt) => opt.text);
                    if (optionLabels.includes("Finalizada")) {
                        currentElement.value = "8"; // Seleccionar Finalizada
                        currentElement.dispatchEvent(new Event('change'));
                        await waitForElement('//*[@id="formulario:final_focus"]');
                        await sleep(500);
                        currentElement = document.getElementById('formulario:final_focus');
                        currentElement.focus();
                    }
                }
                localStorage.setItem("CurrentHotkey", "");


            } else {
                console.log('Element not found formulario:listaEstados_focus');
            }
        });
        // FIN HOTKEY 2 VISAR O FINALIZAR

        // HOTKEY 3 SUBIR DILIGENCIA
        Mousetrap.bind('ctrl+d', async function(e) {
            e.preventDefault(); // Prevent default behavior of hotkey

            currentElement = document.getElementById('formulario:listaFicheros_0:tipoDocumento');
            currentElement.value = "23"; // Seleccionar Diligencia
            currentElement.dispatchEvent(new Event('change'));
            currentElement = document.getElementById('formulario:listaFicheros_0:estado');
            currentElement.value = "2"; // Seleccionar Finalizado
            currentElement.dispatchEvent(new Event('change'));
            currentElement = document.getElementById('formulario:listaFicheros_0:notificar');
            currentElement.value = "0"; // Seleccionar No
            currentElement.dispatchEvent(new Event('change'));
            currentElement = document.getElementById('formulario:listaFicheros_0:nombre');
            currentElement.value = "DILIGENCIA";
            currentElement.dispatchEvent(new Event('change'));
            document.getElementById('formulario:listaFicheros_0:visitaValidada').focus();
            currentElement = document.getElementById('formulario:listaFicheros_0:fechaDiligencia');
            currentElement.focus();

        });
        // FIN HOTKEY 3 SUBIR DILIGENCIA

        // HOTKEY 4 GUARDAR
        Mousetrap.bind('ctrl+s', async function(e) {
            e.preventDefault(); // Prevent default behavior of hotkey

            currentElement = document.getElementById('formulario:j_idt960:guardar:control-guardar');
            currentElement.click();
        });
        // FIN HOTKEY 4 GUARDAR

        // HOTKEY 5 VOLVER
        Mousetrap.bind('ctrl+b', async function(e) {
            e.preventDefault(); // Prevent default behavior of hotkey

            currentElement = document.getElementById('formulario:cmdLinkCancelar');
            if (currentElement) currentElement.click();
            currentElement = document.getElementById('formulario:_id39');
            if (currentElement) currentElement.click();
            currentElement = document.getElementById('formulario:_id36');
            if (currentElement) currentElement.click();
        });
        // FIN HOTKEY 5 VOLVER
    };
    document.head.appendChild(scriptHotkeys);

    //////////////////////////////
    //
    //             FIN
    //    Definicion de hotkeys
    //
    //////////////////////////////

    //////////////////////////////
    //
    //             INICIO
    //    Arreglar campo codigo del formulario de consulta
    //    Para que ponga automaticamente 36/ al principio,
    //    añada ceros a la izquierda y ponga el año actual
    //    si no se especifica
    //
    //////////////////////////////

    function fixCampoOrdenServicio(campo) {
        var trozos = campo.value.split ("/");
        var fecha = new Date();
        if (trozos[0] != null && trozos[1] != null && trozos[1] != ""){
            while (trozos[1].length < 7){
                trozos[1] = "0"+trozos[1];
            }
            if (trozos[2] == null){
                trozos[2] = (fecha.getFullYear()).toString();
                trozos[2] = trozos[2].substring(2,4);
            }
            if(trozos[2].length<2){
                trozos[2] = "0"+trozos[2];
            }
            campo.value = trozos[0]+"/"+trozos[1]+"/"+trozos[2];
        }
    }
    function ifEnter(campo) {
        if (window.event && window.event.keyCode == 13) {
            fixCampoOrdenServicio(campo);
            busquedaAvanzada();
        }
    }

    const scriptFormularioConsulta = document.createElement('script');
    scriptFormularioConsulta.type = 'text/javascript';
    scriptFormularioConsulta.textContent = fixCampoOrdenServicio.toString();
    scriptFormularioConsulta.textContent = scriptFormularioConsulta.textContent + '\n' + ifEnter.toString();
    currentElement = document.getElementById('formulario:strOrdenServicio');
    if (currentElement) {
        currentElement.value = "36/";
        currentElement.setAttribute("onblur", 'javascript:fixCampoOrdenServicio(this)');
        currentElement.setAttribute("onkeypress", 'javascript:ifEnter(this);');
    }
    document.head.appendChild(scriptFormularioConsulta);

    //////////////////////////////
    //
    //             FIN
    //    Arreglar campo codigo del formulario de consulta
    //
    //////////////////////////////

    //////////////////////////////
    //
    //             INICIO
    //    Resaltar campos incorrectos en oficio
    //
    //////////////////////////////

    function resaltarCampo(campo,texto) {
        currentElement = document.getElementById(campo);
        if (currentElement) {
            if (currentElement.tagName == "INPUT") {
                if (currentElement.value == texto) {
                    currentElement.style.backgroundColor = 'salmon';
                }
            }
            if (currentElement.tagName == "SELECT") {
                var selectedText = currentElement.options[currentElement.selectedIndex].text;
                if (selectedText == texto) {
                    currentElement.style.backgroundColor = 'salmon';
                }
            }
        }
    }

    // Obtener tipo de destinatario
    var selectedText = '';
    currentElement = document.getElementById('formulario:cbDestinatarioCMB');
    if (currentElement) {
        selectedText = currentElement.options[currentElement.selectedIndex].text;
    }
    currentElement = document.getElementById('formulario:cbDestinatario_input');
    if (currentElement) {
        selectedText = currentElement.value;
    }
    if (selectedText != '') {
        // Si el informe NO es interno
        if (selectedText != "Jefe de Unidad Especializada de Seguridad y Salud" && selectedText != "Jefe de la Unidad Especializada de Lucha contra el Fraude" && selectedText != "Jefatura inspeccion provincial") {
            resaltarCampo('formulario:sReferencia','');
            resaltarCampo('formulario:asunto','');
            resaltarCampo('formulario:fechaInforme','');
            resaltarCampo('formulario:cbFirmaCMB','Oficio sin ventanilla');
            resaltarCampo('formulario:cbFirmaCMBV','Oficio sin ventanilla');
            resaltarCampo('formulario:direccionDest','');
            resaltarCampo('formulario:codPostalDest','');
            resaltarCampo('formulario:codProvinciaDestCMB','');
            resaltarCampo('formulario:codMunicipioDestCMB','');
            resaltarCampo('formulario:comboNotificarCMB','No');

            // Comprobar que el destinatario no lleve el numero de DNI
            currentElement = document.getElementById('formulario:destinatario');
            if (currentElement.value.match(/[^\d]*\d+[^\d]*/)) {
                currentElement.style.backgroundColor = 'salmon';
            }
        }
    }


    //////////////////////////////
    //
    //             FIN
    //    Resaltar campos incorrectos en oficio
    //
    //////////////////////////////
})();